package config

import (
	"encoding/json"

	"algo-sdk-go/common/apollo"
	"algo-sdk-go/common/constant"

	"github.com/apolloconfig/agollo/v4/storage"
)

var (
	BizDynamicConf = DynamicConf{
		Name: "1",
	}
)

func DynamicCatchApolloChanges(config *Config) {
	AssembleDynamicApolloConfig(config.DynamicConf)
	apollo.ChangedEventRegister(handlerRemoteControllerChanges())
}

var ApolloDynamicConfigMap = map[string]func(*storage.ConfigChange){
	constant.DynamicConf: DynamicConfMethod,
}

func DynamicConfMethod(change *storage.ConfigChange) {
	newVal := change.NewValue.(string)
	apolloDynamicConfig := DynamicConf{}
	err := json.Unmarshal([]byte(newVal), &apolloDynamicConfig)
	if err != nil {
		//logger.LogErrorw("ApolloDynamicMethod DynamicConf err, newVal:%s, 解析 JSON 出错: %+v", newVal, err)
		return
	}
	AssembleDynamicApolloConfig(apolloDynamicConfig)
}

func handlerRemoteControllerChanges() apollo.ChangedEvent {
	eventHandler := func(changes map[string]*storage.ConfigChange) {
		for key, change := range changes {
			execMethod, exist := ApolloDynamicConfigMap[key]
			if exist {
				execMethod(change)
				//logger.LogErrorw("update Apollo data success!", "key", key)
			}
		}
	}
	return apollo.ChangedEvent{
		NameSpace:    "biz",
		EventHandler: eventHandler,
	}
}

func AssembleDynamicApolloConfig(dynamicConf DynamicConf) {
	BizDynamicConf = dynamicConf
}
